//
//  BBActivityCell.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/11/26.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import MapKit
import UIKit
class BBActivityCell: UITableViewCell {
    var activity: BBActivity? {
        didSet {
            let distanceK = (activity?.distance ?? 0) / 1000
            let distanceM = ((activity?.distance ?? 0) % 1000) / 100
            distanceLabel.text = "\(distanceK).\(distanceM)Km"
            timeLabel.text = BBUtils.timeStampToString(timeStamp: (activity?.updateTime)!)
            locationCoordinate2Ds = transCLLocationCoordinate2D(latLonStr: activity?.activityLines)
            drawLine()
        }
    }

    var locationCoordinate2Ds: [CLLocationCoordinate2D]?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = UITableViewCell.SelectionStyle.none
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        contentView.addSubview(backView)
        backView.addSubview(activityTypeLabel)
        backView.addSubview(distanceLabel)
        backView.addSubview(timeLabel)
        backView.addSubview(mapView)

        backView.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: contentView, size: CGSize(width: UIScreen.main.bounds.size.width - 20, height: 190), offset: CGPoint(x: 10, y: 10))
        activityTypeLabel.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: backView, size: nil, offset: CGPoint(x: 10, y: 10))
        distanceLabel.xmg_AlignVertical(type: XMG_AlignType.BottomLeft, referView: activityTypeLabel, size: nil, offset: CGPoint(x: 0, y: 10))
        timeLabel.xmg_AlignHorizontal(type: XMG_AlignType.CenterRight, referView: distanceLabel, size: nil, offset: CGPoint(x: 20, y: 0))
        let width = UIScreen.main.bounds.size.width
        mapView.xmg_AlignVertical(type: XMG_AlignType.BottomLeft, referView: distanceLabel, size: CGSize(width: width - 40, height: 120), offset: CGPoint(x: 0, y: 5))
        mapView.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: backView, size: nil, offset: CGPoint(x: 0, y: -10))
    }

    private lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.layer.cornerRadius = 10.0
        view.layer.masksToBounds = false // 如果是true，阴影不显示
        view.layer.shadowColor = UIColor.lightGray.cgColor // UIColor.init(red: 235/255.0, green: 232/255.0, blue: 235/255.0, alpha: 1).cgColor
        view.layer.shadowOpacity = 1.0
        view.layer.shadowRadius = 5.0
        view.layer.shadowOffset = CGSize(width: 0, height: 0)
        return view
    }()

    private lazy var activityTypeLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 204.0 / 255.0, green: 204.0 / 255.0, blue: 204.0 / 255.0, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 14)
        label.text = "Activity"
        return label
    }()

    private lazy var distanceLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 153.0 / 255.0, green: 153.0 / 255.0, blue: 153.0 / 255.0, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()

    private lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 153.0 / 255.0, green: 153.0 / 255.0, blue: 153.0 / 255.0, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 15)
        label.textAlignment = NSTextAlignment.right
        return label
    }()

    private lazy var mapView: MKMapView = {
        let view = MKMapView()
        // 设置地图样式
        //        case Standard 标准
        //        case Satellite // 卫星
        //        case Hybrid // 混合(标准加卫星)
        //        case SatelliteFlyover 3D立体卫星
        //        case HybridFlyover 3D立体混合
        view.mapType = MKMapType.mutedStandard
        view.isScrollEnabled = false
        view.isRotateEnabled = false
        view.isZoomEnabled = false
        view.delegate = self
        view.isUserInteractionEnabled = false
        return view
    }()

    private func drawLine() {
        if locationCoordinate2Ds != nil {
            let polyline: MKPolyline = MKPolyline(coordinates: locationCoordinate2Ds!, count: locationCoordinate2Ds!.count)
            mapView.addOverlay(polyline)
            let coor1 = locationCoordinate2Ds!.first
            let coor2 = locationCoordinate2Ds!.last
            let coor = locationCoordinate2Ds![locationCoordinate2Ds!.count / 2]
            let distance: Double = distanceBetweenOrderBy(latitude1: (coor1?.latitude)!, longitude1: (coor1?.longitude)!, latitude2: (coor2?.latitude)!, longitude2: (coor2?.longitude)!)
            mapView.setRegion(MKCoordinateRegion(center: coor, latitudinalMeters: distance + 1000, longitudinalMeters: distance + 1000), animated: true)
        }
    }

    private func distanceBetweenOrderBy(latitude1: CLLocationDegrees, longitude1: CLLocationDegrees, latitude2: CLLocationDegrees, longitude2: CLLocationDegrees) -> Double {
        let dd: Double = M_PI / 180
        let x1: Double = latitude1 * dd
        let x2: Double = latitude2 * dd
        let y1: Double = longitude1 * dd
        let y2: Double = longitude2 * dd
        let R: Double = 6371004
        let distance: Double = (2 * R * asin(sqrt(2 - 2 * cos(x1) * cos(x2) * cos(y1 - y2) - 2 * sin(x1) * sin(x2)) / 2))
        return distance
    }

    private func transCLLocationCoordinate2D(latLonStr: String?) -> [CLLocationCoordinate2D]? {
        if latLonStr != nil && latLonStr?.count != 0 {
            let lonAndLatList = latLonStr!.components(separatedBy: ",")
            var locs: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
            for str in lonAndLatList {
                let arr = str.components(separatedBy: ":")
                let longitude = arr.first
                let latitude = arr.last
                let coor = CLLocationCoordinate2D(latitude: Double(latitude!)!, longitude: Double(longitude!)!)
                locs.append(coor)
            }
            return locs
        }
        return nil
    }
}

extension BBActivityCell: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polylineRenderer = MKPolylineRenderer(overlay: overlay)
        polylineRenderer.strokeColor = UIColor.green
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }
}
